import os
import dotenv
from langchain_openai import ChatOpenAI
from langchain_community.document_loaders import WebBaseLoader
from langchain_core.tools import tool
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents import AgentExecutor, create_openai_functions_agent

dotenv.load_dotenv()
openai_url = os.getenv('OPENAI_API_BASE')
api_key = os.getenv('OPENAI_API_KEY')

@tool
def web_loader(url: str) -> str:
    """url网页的内容"""
    loader = WebBaseLoader(url)
    docs = loader.load()
    return docs[0].page_content


#绑定tool
llm = ChatOpenAI(openai_api_key=api_key,openai_api_base=openai_url)
tools = [web_loader]
llm_with_tools = llm.bind_tools(tools)


prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "你是一个擅长对长文做总结的智能助手，可以精确提炼出长文中的要点。注意，请使用markdown格式返回结果。",
        ),
        ("placeholder", "{chat_history}"),
        ("user", "{input}"),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ]
)


agent = create_openai_functions_agent(llm_with_tools, tools, prompt)

agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=False)

res = agent_executor.invoke(
    {
        "input": "这个链接讲了什么内容？ https://blog.csdn.net/xindoo/article/details/138356308?spm=1001.2014.3001.5501"
    }
)

print(res)



